package com.wise.service.cms.content.menus;

import com.wise.entities.content.Menu;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.summer.v1.cms.content.menus.ListMenus;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
@SummerService
public class ListMenusService implements SummerServiceBean<ListMenus> {
	@Override
	public void sum(ListMenus model) {
		//查询菜单，若有条件查询可加入条件
		List<Menu> allMenu = getAllMenu();
		//父菜单集合
		List<Menu> menuList = getChild(allMenu, it -> StringUtils.isEmpty(it.getParentId()));

		model.setSummerResult(menuList);
	}

	/**
	 * 查询所有菜单
	 *
	 * @return
	 */
	private List<Menu> getAllMenu() {
		SqlSelect selec = SqlSelect.selec("*")
				.fromClassName(Menu.class)
				.eqLang(Menu._lang);
		return DaoList.s(Menu.class, selec);
	}

	/**
	 * 获取子菜单集合
	 *
	 * @param allMenu   所有菜单集合
	 * @param predicate
	 * @return
	 */
	private List<Menu> getChild(List<Menu> allMenu, Predicate<Menu> predicate) {
		List<Menu> childList = allMenu.stream()
				.filter(predicate)
				.sorted(order().thenComparing(Menu::getId))
				.collect(Collectors.toList());

		/* 递归 */
		for (Menu menu : childList) {
			menu.setChildList(getChild(allMenu, it -> Objects.equals(menu.getId(), it.getParentId())));
		}
		/* 退出递归条件 */
		return CollectionUtils.isEmpty(childList) ? null : childList;

	}

	/**
	 * 菜单排序
	 */
	private Comparator<Menu> order() {
		return (o1, o2) -> {
			if (!o1.getSeqencing().equals(o2.getSeqencing())) {
				return o1.getSeqencing() - o2.getSeqencing();
			}
			return 0;
		};
	}
}
